<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-plus" @click="handleUpdate(null)">添加</el-button>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="角色名称" v-model="filters.like$title"></el-input>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>
    <el-table :data="list" @sort-change="sortChange" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">
      <el-table-column align="center" type="index" label="序号" width="60">
      </el-table-column>

      <el-table-column prop="roleName" align="center" label="角色名称" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.roleName}}</span>
        </template>
      </el-table-column>


      <el-table-column prop="createTime" align="center" label="创建时间" width="160">
        <template slot-scope="scope">
          <span>{{scope.row.createTime|parseTime}}</span>
        </template>
      </el-table-column>


      <el-table-column prop="intro" align="center" label="备注" width="400">
        <template slot-scope="scope">
          <span>{{scope.row.description}}</span>
        </template>
      </el-table-column>


      <el-table-column align="center" label="操作" width="250" class-name="small-padding">
        <template slot-scope="scope">
          <div class="text-left " style="padding-left:20px;">
              <el-button type="success" size="mini" @click="editPerm(scope.row)">授权</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)" v-if="scope.row.id!=1">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)" v-if="scope.row.id!=1">删除</el-button>
          </div>
          
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="params.page"
        :page-sizes="[10,20,30,50]" :page-size="params.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="isEditing?'修改':'添加'" :visible.sync="dialogFormVisible">
      <el-form class="dialog-form" :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px">

        <el-form-item label="角色名称" prop="roleName">


          <el-input v-model="temp.roleName" placeholder="请输入供应商名称"></el-input>


        </el-form-item>
        <el-form-item label="备注" prop="description">


          <el-input v-model="temp.description" placeholder="在这里写备注" type="textarea" :rows="3"></el-input>


        </el-form-item>

        <el-form-item label="权限" prop="permissions" v-if="!isEditing">

          <el-tabs v-model="activePermission" @tab-click="handleClick" :value="0">

            <el-tab-pane v-for="perm in permissions" :label="perm.permissionName" :key="perm.id" :name="perm.id+''">
              <el-checkbox v-model="permChecked['checkbox-'+perm.id]" @change="changeChecked(perm,$event)">全选</el-checkbox>

              <el-tree :data="perm.childList" show-checkbox node-key="id" :ref="'tree-'+perm.id" :default-expand-all="true" :props="defaultProps">
              </el-tree>
            </el-tab-pane>
          </el-tabs>


        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="submiting" @click="submitFormAction">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改权限" :visible.sync="showEditPerm">
          <div style="padding:0 0 20px 0">
            角色名:{{currentEditPerm.roleName}}
          </div>
          <el-tabs v-model="activePermission" @tab-click="handleClick" :value="0">

            <el-tab-pane v-for="perm in permissions" :label="perm.permissionName" :key="perm.id" :name="perm.id+''">
              <el-checkbox v-model="permChecked['checkbox-'+perm.id]" @change="changeChecked(perm,$event)">全选</el-checkbox>

              <el-tree :data="perm.childList" show-checkbox node-key="id" :ref="'tree-'+perm.id" :default-expand-all="true" :props="defaultProps">
              </el-tree>
            </el-tab-pane>
          </el-tabs>
        <div slot="footer" class="dialog-footer">
        <el-button @click="showEditPerm = false">取消</el-button>
        <el-button type="primary" :loading="submiting" @click="submitEditPermAction">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      defaultProps: {
        children: "childList",
        label: "permissionName"
      },
      total: 0,
      showEditPerm: false,
      currentEditPerm: {},
      permChecked: {},
      activePermission: "",
      permissions: [],
      temp: {
        id: "",

        roleName: "",

        permissions: ""
      },

      rules: {
        roleName: [
          {
            required: true,
            message: "角色名称不能为空",
            trigger: "change"
          },
          {
            max: 20,
            message: "角色名称不能超过20个字",
            trigger: "change"
          }
        ]
        // ,
        // permissions: [
        //   {
        //     required: true,
        //     message: "请选择权限",
        //     trigger: "change"
        //   }
        // ]
      }
    };
  },
  created() {
    this.$get("/admin/admin_role/permissions/list").then(data => {
      this.permissions = data;
      this.activePermission = this.permissions[0].id + "";
    });
    this.init("admin_role", 0).loadData();
  },
  filters: {},
  methods: {
    submitEditPermAction() {
      let ids = [];
      this.permissions.forEach(per => {
        let id = "tree-" + per.id;
        let keys = this.$refs[id][0].getCheckedKeys();
        if (keys.length) {
          ids.push(per.id);
          let keys2 = this.$refs[id][0].getHalfCheckedKeys();
          if(keys2.length){
            ids.push(...keys2);
          }
          ids.push(...keys);
        }
      });
      let permissions = ids.join(",");
      this.submiting = true;
      this.$post("/admin/admin_role/empower", {
        roleId: this.currentEditPerm.id,
        permissions
      })
        .then(_ => {
          this.$$notify();
          this.showEditPerm = false;
          this.submiting = false;
          this.loadData();
        })
        .catch(_ => {
          this.submiting = false;
        });
    },
    editPerm(row) {
      this.showEditPerm = true;
      this.currentEditPerm = row;
      let ids = [];
      row.permList &&
        row.permList.forEach(el => {
          ids.push(el.id);
        });

      setTimeout(_ => {
        this.permissions.forEach(per => {
          let id = "tree-" + per.id;
          // if (
          //   (this.$refs[id][0].getCheckedKeys().length == per.childList.length)
          // ) {
          //   this.$set(this.permChecked, "checkbox-" + per.id, true);
          // }else{
          //   this.$set(this.permChecked, "checkbox-" + per.id, false);
          // }
          this.$refs[id][0].setCheckedKeys(ids);
        });
      }, 10);
    },
    __onHandleUpdate(row) {
      if (row) {
        return;
      } else {
        setTimeout(_ => {
          this.permissions.forEach(per => {
            let id = "tree-" + per.id;
            // if (
            //   (this.$refs[id][0].getCheckedKeys().length == per.childList.length)
            // ) {
            //   this.$set(this.permChecked, "checkbox-" + per.id, true);
            // }else{
            //   this.$set(this.permChecked, "checkbox-" + per.id, false);
            // }
            this.$refs[id][0].setCheckedKeys([]);
          });
        }, 10);
      }

      // this.permissions.forEach(per=>{
      //     per.childList && per.childList.forEach(child=>{

      //     })
      //     let id = 'tree-'+ per.id;

      //     ids.push(...this.$refs[id][0].getCheckedKeys());
      // });
    },
    __onFormSubmit() {
      if (this.isEditing) {
        return;
      }
      let ids = [];
      this.permissions.forEach(per => {
        let id = "tree-" + per.id;
        let keys = this.$refs[id][0].getCheckedKeys();
        if (keys.length) {
          ids.push(per.id);
          let keys2 = this.$refs[id][0].getHalfCheckedKeys();
          if(keys2.length){
            ids.push(...keys2);
          }
          ids.push(...keys);
        }
      });
      this.temp.permissions = ids.join(",");
    },
    handleClick() {},
    changeChecked(perm, event) {
      let ids = [];
      if (event) {
        perm.childList &&
          perm.childList.forEach(element => {
            ids.push(element.id);
          });
      }
      this.$refs["tree-" + perm.id][0].setCheckedKeys(ids);
    }
  }
};
</script>
